<template>
  <div>
    <Spin :spinning="loading" tip="Loading...">
      <div style="margin-bottom: 1rem;"></div>
    <!-- 搜索 -->
    <BreakSpace label="经销商信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel" :list="formList" :cols="2" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle"/>
    <BreakSpace label="配件列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="false"
      height="auto"
      :isPagination=false
      :isSelectColumn=false>
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">添加</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visibleAdd" :title="'经销商选择'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DealerList @close="closeAdd" @save="saveAdd"></DealerList>
    </BaseDialog>
    <BaseDialog :visible.sync="peijianFlag" :title="'配件选择'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <PeiJianSelect @close="closeAdd1" @save="saveAdd1"></PeiJianSelect>
    </BaseDialog>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
      <multiuse-button @click="closeDialog">关 闭</multiuse-button>
    </div>
    </Spin>
  </div>
</template>
<script>
import { editSave ,huixian} from '@/api/claim/factory/AuthDealerMaintain';
import { isFormEmpty } from '@/utils/index';
import PeiJianSelect from '@/pages/claimDemage/tools/vehicle.vue';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
export default {
  props: [ 'rowData'],
  components: {
    DealerList,PeiJianSelect
  },
  data() {
    return {
      loading: false,
      saveData: {}, //保存对象
      dataList: [],
      editRow: {},
      aaIds: {},
      visible: false,
      visibleDrawer: false,
      collapse: false,
      peijianFlag: false,
      infoId: null,
      formList: this.createFormList(),
      flterValue: {}, //参数
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      dialogTitle: '选择车辆',
      visibleAdd: false,
      obj: {
        rpPtTypeDTOS:[]
      }
    };
  },
  created() {

    this.getDatabyId(this.rowData.dealerCode);
  },
  methods: {
    async getDatabyId(dealerCode) {
      this.loading = true;
      // this.flag =2;
      let res = await huixian(dealerCode);
      this.editRow = res.data;
      this.createdBy = res.data.createdBy;
      //为form赋值
      for (let i in res.data) {
        this.formList.map(y => {
          if (i == y.fieldName) {
            y.initialValue = res.data[i];
          }
        });
      };
      //原来是partid  但是发现partid 没回来 就换成了aaId
      let records2 = res.data.partList[0].partCode==null?[{partName:'全部',partCode:'全部'}]:res.data.partList;
      // if(res.data.partList[0].partId==null){
      //   this.flag =1;
      // }
      let str = '';
      res.data.partList.map(x => {
        str += x.aaId + ',';
      });
this.aaIds=str;
      if (isFormEmpty(records2)) {
        records2 = [];
      }
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records2);
      this.loading = false;
    },

    formChangeHandle(val) {
      this.saveData = val;
    },
    deleteFun(costItem) {
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE([costItem]);
    },
    chooseDealerNo() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    closeAdd1() {
      this.peijianFlag = false;
     // this.fetchParams = { ...this.fetchParams };
    },
    saveAdd(obj) {
      this.formList.map(x => {
        if ('dealerCode' == x.fieldName) {
          x.initialValue = obj[0].dealerCode;
        }
        if ('dealerName' == x.fieldName) {
          x.initialValue = obj[0].dealerName;
        }

      })
      this.visibleAdd=false;
    },
    saveAdd1(obj) {
      let falg = true ;

      this.$refs.table.$refs.pageTable.list.map(x => {
        if(obj[0].partCode == x.partCode){
          falg = false;
          this.$notify.error({ title: '提示信息', message: '配件选择重复' });
        }
      });
      if(falg){
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(obj);
      }
      this.peijianFlag = false;
    },
    add() {
      this.peijianFlag=true;
    },
    //保存
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      let arr = [];
      this.$refs.table.$refs.pageTable.list.map(x => {
        if(x.partCode!='全部'){
          arr.push(x);
        }
      });

       this.saveData.partList = arr;


      for (let a in this.editRow) {
        if (this.saveData[a]) {
          this.editRow[a] = this.saveData[a];
        }
      }

      for (let a in this.editRow.partList){
        this.editRow.partList[a].aaId='';
      }
      // if(this.flag ==2){
        this.editRow.delIds=this.aaIds;
      // }
      if(this.editRow.partList.length==0){
        this.editRow.partList.push({dealerCode:this.editRow.dealerCode,dealerName:this.editRow.dealerName})
      }
      this.editRow.createdBy = this.createdBy;
      if (this.saveData.dealerCode!=null ) {
        this.loading = true;
        let res = await editSave(this.editRow);
        if (res.resultCode === 200) {
          this.$emit('save');
          return this.$notify.success({ title: '提示信息', message: '保存成功' });
        } else {
          this.loading = false;
          // this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
          // this.closeDialog();
        }
      }else {
        // return this.$notify.warning({ title: '提示信息', message: '有未校验通过的信息' });
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          rules: [{ required: true, message: '请填经销商代码', trigger: 'blur' }],
          placeholder: '请输入', readonly: true,
          initialValue: '',
          unitRender: p => {
            return (
              <div>
              <multiuse-button icon="el-icon-search" onClick={() => this.chooseDealerNo()} />
            </div>
          );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          readonly: true,
          fieldName: 'dealerName',
          placeholder: '请输入',
          rules: [{ required: true, message: '请填经销商名称', trigger: 'blur' }],
          initialValue: '' ,
          disabled: true // 置灰
        }
      ];
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          width: 80,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text"  onClick={() => this.deleteFun(props.row)}>
                  删除
                </multiuse-button>
              </div>
          );
          }
        },
        { title: '配件代码', dataIndex: 'partCode', sorter: true },
        { title: '配件名称', dataIndex: 'partName', sorter: true }

      ];
    }
  }
};
</script>

